﻿using System;
using System.Windows;
using System.Collections.Specialized;

namespace Monti.MVVM.Commands
{
   /// <summary>
   /// Defines a collection of command behaviors.
   /// </summary>
   public class CommandBehaviorCollection
   {
      /// <summary>
      /// Behaviors Read-Only Dependency Property
      /// As you can see the Attached readonly property has a name registered different (BehaviorsInternal)
      /// than the property name, this is a tricks os that we can construct the collection as we want
      /// Read more about this here http://wekempf.spaces.live.com/blog/cns!D18C3EC06EA971CF!468.entry
      /// </summary>
      private static readonly DependencyPropertyKey s_BehaviorsPropertyKey
          = DependencyProperty.RegisterAttachedReadOnly ("BehaviorsInternal", typeof (CommandBehaviorList), typeof (CommandBehaviorCollection),
              new FrameworkPropertyMetadata ((CommandBehaviorList)null));

      /// <summary>
      /// Attached behaviors.
      /// </summary>
      public static readonly DependencyProperty BehaviorsProperty
          = s_BehaviorsPropertyKey.DependencyProperty;

      /// <summary>
      /// Gets the Behaviors property.  
      /// Here we initialze the collection and set the Owner property
      /// </summary>
      public static CommandBehaviorList GetBehaviors (DependencyObject d)
      {
         if (d == null)
            throw new InvalidOperationException ("The dependency object trying to attach to is set to null");

         var collection = d.GetValue (BehaviorsProperty) as CommandBehaviorList;
         if (collection == null)
         {
            collection = new CommandBehaviorList { Owner = d };
            SetBehaviors (d, collection);
         }
         return collection;
      }

      /// <summary>
      /// Provides a secure method for setting the Behaviors property.  
      /// This dependency property indicates ....
      /// </summary>
      private static void SetBehaviors (DependencyObject d, CommandBehaviorList value)
      {
         d.SetValue (s_BehaviorsPropertyKey, value);
         var collection = (INotifyCollectionChanged)value;
         collection.CollectionChanged += CollectionChanged;
      }

      static void CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
      {
         var sourceCollection = (CommandBehaviorList)sender;
         switch (e.Action)
         {
            //when an item(s) is added we need to set the Owner property implicitly
            case NotifyCollectionChangedAction.Add:
               if (e.NewItems != null)
                  foreach (CommandBehavior item in e.NewItems)
                     item.Owner = sourceCollection.Owner;
               break;
            //when an item(s) is removed we should Dispose the CommandBehavior
            case NotifyCollectionChangedAction.Remove:
               if (e.OldItems != null)
                  foreach (CommandBehavior item in e.OldItems)
                     item.Behavior.Dispose ();
               break;

            //here we have to set the owner property to the new item and unregister the old item
            case NotifyCollectionChangedAction.Replace:
               if (e.NewItems != null)
                  foreach (CommandBehavior item in e.NewItems)
                     item.Owner = sourceCollection.Owner;

               if (e.OldItems != null)
                  foreach (CommandBehavior item in e.OldItems)
                     item.Behavior.Dispose ();
               break;

            //when an item(s) is removed we should Dispose the CommandBehavior
            case NotifyCollectionChangedAction.Reset:
               if (e.OldItems != null)
                  foreach (CommandBehavior item in e.OldItems)
                     item.Behavior.Dispose ();
               break;
         }
      }

   }

   /// <summary>
   /// Collection to store the list of behaviors. This is done so that you can intiniate it from XAML
   /// This inherits from freezable so that it gets inheritance context for DataBinding to work
   /// </summary>
   public class CommandBehaviorList : FreezableCollection<CommandBehavior>
   {
      /// <summary>
      /// Gets or sets the Owner of the binding
      /// </summary>
      public DependencyObject Owner { get; set; }
   }
}
